import React from "react";
import md5 from 'md5'
import { Form, Input, Button, Row, Col, Icon } from 'antd';
import { getStuForgetValidCode, sendForgetPasswordSmsCode, saveStuNewPassword } from '../api';
import { Link } from 'react-router-dom'

const FormItem = Form.Item

class ForgetPassword extends React.Component {

  constructor(props) {
    super(props)
    this.state = {
      validCodeImg: '',
      mobilePhoneValidCodeFlag: true,
      seconds: '获取验证码',
    }
  }

  componentDidMount() {
    this.getStuForgetValidCode()
  }

  getStuForgetValidCode = () => {
    getStuForgetValidCode(res => {
      this.setState({
        validCodeImg: res.data
      })
    })
  }

  // 获取手机验证码
  sendForgetPasswordSmsCode = () => {
    const form = this.props.form;
    const mobilePhone = form.getFieldValue('mobilePhone')
    let timer = null
    this.setState({
      seconds: 120,
      mobilePhoneValidCodeFlag: true,
    }, () => {
      sendForgetPasswordSmsCode({ mobilePhone }, ()=>{
        timer = setInterval(() => {
          if(this.state.seconds===0){
            this.setState({
              seconds: '重新获取',
              mobilePhoneValidCodeFlag: false
            })
            clearInterval(timer)
            timer = null
            return
          }
          this.setState((prevState)=>({seconds: prevState.seconds-1}))
        }, 1000)
      }, () => {
        setTimeout(() => {
          this.setState({
            seconds: '重新获取',
            mobilePhoneValidCodeFlag: false
          })
        }, 1000);
      })
    })
  }

  // 自定义手机号校验
  validatePhone = (rule, value, callback) => {
    const seconds = this.state.seconds
    if(value && !/^1([38]\d|5[0-35-9]|7[3678])\d{8}$/.test(value)){
      this.setState({
        mobilePhoneValidCodeFlag: true
      })
      callback('请输入正确的11位手机号')
    }else{
      this.setState({
        mobilePhoneValidCodeFlag: typeof seconds === 'string' ? false : true
      })
      callback()
    }
  }

  //
  validatePasswordAgain = (rule, value, callback) => {
    const form = this.props.form;
    if (value && value !== form.getFieldValue('password')) {
      callback('两次密码输入不一致！');
    } else {
      callback();
    }
  }

  handleSubmit = (e) => {
    e.preventDefault();
    const form = this.props.form
    form.validateFields((err, values) => {
      if (!err) {
        const { password:_password, mobilePhone, validCode, smsCode } = values
        saveStuNewPassword({
          password: md5(_password), 
          mobilePhone, 
          validCode, 
          smsCode,
        }, res => {
          this.props.history.push('/student/password_login')
          form.resetFields()
        }, (err) => {
          if(err.code == 6){
            form.setFields({
              validCode: {
                value: '',
                errors: [new Error(err.msg)],
              }
            })
          }else if(err.code == 2){
            form.setFields({
              smsCode: {
                value: '',
                errors: [new Error(err.msg)],
              }
            })
          }
          this.getStuForgetValidCode();
        })
      }
    });
  }

  render() {

    const { validCodeImg, seconds, mobilePhoneValidCodeFlag } = this.state
    const { getFieldDecorator } = this.props.form

    return (
      <div className="student-form">
        <Link to="/home" className="close"></Link>
        <p className="title">重置密码</p>
        <Form onSubmit={this.handleSubmit} onKeyDown={e=>{if(e.keyCode==13){e.preventDefault()}}}>
          
          <div className="reset-input-container">
            <FormItem style={{ marginBottom: 0, height: 64 }}>
              <Row gutter={16}>
                <Col span={16}>
                  {getFieldDecorator("validCode", {
                    rules: [{ required: true, message: "图形验证码不能为空" }]
                  })(<p><Input 
                    size="large"
                    prefix={<Icon type="lock" style={{ color: '#bbb', fontSize: 18 }} />}
                    placeholder="请输入图形验证码" autoComplete="off" /></p>)}
                </Col>
                <Col span={8} onClick={this.getStuForgetValidCode}>
                  <img
                    style={{ width: 100, height: 40, cursor: "pointer" }}
                    src={validCodeImg}
                    alt=""
                  />
                </Col>
              </Row>
            </FormItem>
          </div>
          <div className="reset-input-container"> 
            <FormItem style={{ marginBottom: 0, height: 64 }}>
              <Row gutter={16}>
                <Col span={16}>
                  {getFieldDecorator("smsCode", {
                    rules: [{ required: true, message: "手机验证码不能为空" }]
                  })(<p><Input 
                    size="large"
                    prefix={<Icon type="lock" style={{ color: '#bbb', fontSize: 18 }} />}
                    placeholder="请输入6位手机验证码" autoComplete="off" /></p>)}
                </Col>
                <Col span={6}>
                  <Button
                    style={{ width: 100, height: 40, borderRadius: 2 }}
                    type="primary"
                    disabled={mobilePhoneValidCodeFlag}
                    onClick={this.sendForgetPasswordSmsCode}
                  >
                    {seconds}
                  </Button>
                </Col>
              </Row>
            </FormItem>
          </div>
          <div className="reset-mobile-phone-container">
            <FormItem style={{ marginBottom: 0, height: 64 }}>
              {getFieldDecorator("mobilePhone", {
                rules: [
                  { required: true, message: "手机号码不能为空" },
                  { validator: this.validatePhone }
                ]
              })(<p><Input 
                size="large"
                prefix={<Icon type="lock" style={{ color: '#bbb', fontSize: 18 }} />}
                placeholder="请输入注册时的手机号码" autoComplete="off" /></p>)}
            </FormItem>
          </div>
          <FormItem style={{ marginBottom: 30, height: 64 }}>
            {getFieldDecorator("password", {
              rules: [
                { required: true, message: "密码不能为空" },
                { pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,30}$/, message: '密码应为6-30位数字字母组合' }
              ]
            })(<p><Input 
              size="large"
              prefix={<Icon type="lock" style={{ color: '#bbb', fontSize: 18 }} />}
              type="password" placeholder="请输入密码" autoComplete="off" /></p>)}
          </FormItem>
          {/* <FormItem style={{ marginBottom: 0, height: 64 }}>
            {getFieldDecorator("passwordAgain", {
              rules: [
                { required: true, message: "二次密码不能为空" },
                { validator: this.validatePasswordAgain }
              ]
            })(<p><Input 
              size="large"
              prefix={<Icon type="lock" style={{ color: '#bbb', fontSize: 18 }} />}
              type="password" placeholder="再次确认密码" autoComplete="off" /></p>)}
          </FormItem> */}
          <Button type="primary" className="btn" htmlType="submit">确定</Button>
        </Form>
      </div>
    );
  }
}

const WarpForgetPassword = Form.create()(ForgetPassword)

export default WarpForgetPassword
